package com.xcenter.cabinet.file.util;

import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import com.xcenter.cabinet.util.DateUtil;

public class FileUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);
	
	/**
	 * 生成日期格式的路径
	 * eg： 2017/07/09
	 * @return 
	 */
	private static String genDatePath() {
		return DateUtil.getFormatCurrDate().replace("-", File.separator);
	}
	
	/**
	 * 生成文件夹全路径
	 * @param root
	 * @param bucket
	 * @return
	 */
	public static String genFullFolderPath(String root, String bucket) {
		return root + File.separator + bucket + File.separator + genDatePath();
	}
	
	/**
	 * 生成文件夹路径
	 * @param root
	 * @param bucket
	 * @return
	 */
	public static String genFolderPath(String bucket) {
		return bucket + File.separator + genDatePath();
	}
	
	public static String getSuffixWithDot(String filename) {
		int index = filename.lastIndexOf(".");
		if(index == -1) {
			return "";
		}
		return filename.substring(index, filename.length());
	}
	
	public static String getMd5(MultipartFile file) {
		try {
			return DigestUtils.md5DigestAsHex(file.getBytes());
		} catch (IOException e) {
//			e.printStackTrace();
			return "unknow";
		}
	}
	
	/**
	 * 存储文件
	 * @param root
	 * @param bucket
	 * @param files
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	public static String[] storeFiles(String folderPath, Long[] ids, MultipartFile[] files) throws IllegalStateException, IOException {
		logger.info("[存储文件]开始...");
		File folder = new File(folderPath);
		if(!folder.exists()) {
			folder.mkdirs();
		}
		logger.info("[存储文件]位置:{}", folderPath);
		int len = files.length;
		String[] filenames = new String[len];
		for (int i = 0; i < len; i++) {
			MultipartFile mf = files[i];
			if(mf == null) {
				continue;
			}
			String filename = ids[i] + getSuffixWithDot(mf.getOriginalFilename());
			filenames[i] = filename;
			mf.transferTo(new File(folderPath + File.separator + filename));
		}
		logger.info("[存储文件]结束");
		return filenames;
	}
	
}
